<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- <h2>
        员工
      </h2> -->
      <!-- <PageTools :show-before="true">
        <template v-slot:before>
          {{ '左侧' }}
        </template>
        <template v-slot:after>
          {{ '右侧' }}
        </template>
      </PageTools> -->

      <PageTools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click.native="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click.native="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click.native="isShowDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <!-- <el-table border :data="employeesUserList" height="calc(100vh - 300px )"> -->
        <el-table border :data="employeesUserList" max-height="650">
          <el-table-column v-slot="{ $index }" label="序号" sortable="" type="index">
            {{ (pageConfig.page-1) * pageConfig.size + $index+1 }}
          </el-table-column>
          <el-table-column label="头像" sortable="" prop="staffPhoto" width="100">
            <template v-slot="{row}">
              <div>
                <img
                  v-fixImg="require('@/assets/common/bigUserHeader.png')"
                  :src="row.staffPhoto"
                  alt=""
                  style="width:100%;border-radius:50%"
                  @click="showCode(row.staffPhoto)"
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />

          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <!-- 作用域插槽的使用 -->
          <!-- <el-table-column v-slot="obj" label="聘用形式" sortable="" prop="formOfEmployment">
            {{ obj.row.formOfEmployment===1? '正式员工' : '临时员工' }}
          </el-table-column> -->

          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="obj">
              <!--  | 这个是管道符号 -->
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="inServiceStatus">
            <!-- 作用域插槽的使用 default表示默认-->
            <template #default="obj">
              <!-- {{ obj.row.inServiceStatus }} -->

              <!-- element UI 开关的使用 -->
              <el-switch
                v-model="obj.row.inServiceStatus"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="obj">
              <el-button type="text" size="small" @click.native="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="positive(obj.row.id)">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(obj.row.id)">角色</el-button>
              <el-button v-if="checkPermission('delEmployee')" type="text" size="small" @click.native="delEmployees(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="sizes, prev, pager, next"
            :page-sizes="pageSizes"
            :page-size="pageConfig.size"
            :total="total"
            :current-page="pageConfig.page"
            @size-change="sizeChange"
            @current-change="currentChange"
          />

        </el-row>
      </el-card>
      <!-- 新增弹框 -->
      <addEmployee :is-show-dialog="isShowDialog" />
      <!-- 图片转二维码弹框 -->
      <el-dialog title="二维码" :visible.sync="isShowCode" width="20%">
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <assignRole ref="assignRole" :is-show-role.sync="isShowRole" />

      <!-- 转正 -->
      <positive :is-show-positive="isShowPositive" />
    </div>
  </div>
</template>

<script>
// 转二维码的第三方模块
import QRCode from 'qrcode'
import EnumEmployees from '@/api/constant/employees'
// import PageTools from '@/components/PageTools'
import { delEmployee, getEmployeesUserList } from '@/api/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
import Positive from './components/positive.vue'
// mixin局部混入
// import Mixin from '@/mixin'

export default {
  // 局部过滤器
  filters: {
    // formatDate(oldval) {
    //   return oldval.split('T')[0]
    // }
  },
  components: {
    addEmployee,
    assignRole,
    Positive
  },
  // mixin局部混入
  // mixins: [Mixin],

  data() {
    return {
      employeesUserList: [],
      pageConfig: {
        page: Number(localStorage.getItem('currentPage')) || 1,
        size: 5
      },
      total: 0,
      pageSizes: [5, 10, 20, 40],
      isShowDialog: false,
      isShowCode: false,
      isShowRole: false,
      isShowPositive: false
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 控制用户按钮的权限设置
    // checkPermission(val) {
    //   // console.log(this.$store.state.user.userInfo.roles.points)
    //   const roles = this.$store.state.user.userInfo.roles
    //   return roles ? roles.points.includes(val) : false
    // },

    // 转正
    positive(id) {
      console.log(id)
      this.isShowPositive = true
    },
    // 角色分配
    async showRole(id) {
      // console.log(id)
      await this.$refs.assignRole.getCheckList(id)
      this.isShowRole = true
    },
    // 二维码
    showCode(url) {
      if (url) {
        // console.log(1)
        this.isShowCode = true
        this.$nextTick(() => {
          const canvas = this.$refs.canvas
          QRCode.toCanvas(canvas, url, {
            color: {
              dark: '#66b1ff' // Blue dots
              // light: '#0000' // Transparent background
            }
          })
        })
      }
    },
    // 删除
    async delEmployees(id) {
      // console.log(id)
      await this.$confirm('请问是否删除')

      if (this.employeesUserList.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      await delEmployee(id)

      this.getEmployees()
      this.$message.success('删除成功')
    },
    // 导出
    async exportExcel() {
      const { rows } = await getEmployeesUserList({ page: 1,
        size: this.total })
      // console.log(rows)
      const header = ['手机号', '姓名', '工号', '聘用形式', '部门', '入职日期']

      const data = rows.map(user => {
        return this.userType(user)
      })
      // console.log(data)

      // 导出
      export_json_to_excel({
        header,
        data,
        filename: '员工列表'
      })

      // export_json_to_excel({
      //   header: ['名字', '年龄'],
      //   data: [
      //     ['tom', '23'],
      //     ['jack', '18']
      //   ],
      // filename: '员工列表'
      // })
    },
    userType(user) {
      const userData = []
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName',
        '入职日期': 'timeOfEntry'
      }

      for (const key in dict) {
        const enKey = dict[key]
        let value = user[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployees.hireType.find(item => Number(item.id) === Number(value))
          // console.log(obj)
          value = obj ? obj.value : '未知'
          userData.push(value)
        } else if (enKey === 'departmentName') {
          userData.push(value || '未分布')
        } else if (enKey === 'timeOfEntry') {
          const times = formatDate(value)
          // console.log(times)
          userData.push(times)
        } else {
          userData.push(value)
        }
      }
      // console.log(userData)
      return userData
    },

    // 获取员工列表
    async getEmployees() {
      const { rows, total } = await getEmployeesUserList(this.pageConfig)
      // console.log(res)

      this.employeesUserList = rows.map(item => {
      // 本地服务器没有inServiceStatus属性,需要手动添加
        const statu = Math.round(Math.random())
        // console.log(statu)
        return {
          ...item,
          inServiceStatus: item.inServiceStatus || statu
        }
      })
      // console.log(this.employeesUserList)
      this.total = total
    },
    sizeChange(pageSize) {
      // console.log(page)
      this.pageConfig.size = pageSize
      this.getEmployees()
    },

    formatEmployment(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式员工' : '临时员工'

      // 枚举数据
      const obj = EnumEmployees.hireType.find(item => Number(item.id) === Number(cellValue))
      return obj ? obj.value : '未知'
    },

    // 跳转页码
    currentChange(val) {
      // console.log(val)
      // 保存页码到本地
      localStorage.setItem('currentPage', val)
      this.pageConfig.page = val
      this.getEmployees()
    }
  }
}
</script>

<style lang="scss" scoped>
// ::v-deep .el-table{
//   max-height: 650px;
// }
</style>

